package utils;

import common.ListNode;

public class ListNodeUtil {
    //将数组转换为链表
    public static ListNode transformArrayToListNode(Integer[] arr){
        if(arr.length == 0)     return null;
        ListNode head = new ListNode();
        head.val = arr[0];
        ListNode node = head;
        for(int i=1;i<arr.length;i++){
            node.next = new ListNode();
            node = node.next;
            node.val = arr[i];
        }
        return head;
    }

    //打印链表
    public static void printListNode(ListNode head){
        if(head == null){
            System.out.println("null");
            return;
        }
        while(head.next != null){
            System.out.print(head.val + ",");
            head = head.next;
        }
        System.out.println(head.val);
    }

    //获取链表的中间节点，也就是前半部分的尾结点
    public static ListNode endOfFirstHalf(ListNode head){
        if(head == null)    return null;
        //通过快慢指针获取，慢指针一次前进一格，快指针一次前进两格
        ListNode slow = head;
        ListNode fast = head;
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    //反转链表
    public static ListNode reverseListNode(ListNode head){
        ListNode curr = head;
        ListNode prev = null;
        while(curr != null){
            ListNode tempNext = curr.next;
            curr.next = prev;
            prev = curr;
            curr = tempNext;
        }
        return prev;
    }

    //合并两个有序链表
    public static ListNode mergeListNode(ListNode headA,ListNode headB){
        ListNode a = headA;
        ListNode b = headB;
        ListNode newHead = new ListNode(0);
        ListNode temp = newHead;
        while(a != null && b != null){
            if(a.val <= b.val){
                temp.next = a;
                a = a.next;
            }else{
                temp.next = b;
                b = b.next;
            }
            temp = temp.next;
        }
        if(a != null){
            temp.next = a;
        }
        if(b != null){
            temp.next = b;
        }
        return newHead.next;
    }
}
